package com.tenton.servlet;

import com.tenton.pojo.Book;
import com.tenton.service.BookService;
import com.tenton.service.Impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Date: 2021/1/19
 * @Author: Tenton
 * @Description: 根据用户Id查询用户信息
 */
@WebServlet(name = "SelectBookByIdServlet",urlPatterns = "/selectBookByIdServlet")
public class SelectBookByIdServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //用户Id
        String bookId = request.getParameter("id");
        Integer bookid = null;
        //判断是否为空，然后再进行转化为int类型
        if(bookId !=null && !bookId.equals("")){
            bookid = Integer.parseInt(bookId);
        }
        BookService bookService = new BookServiceImpl();
        if (bookid != null) {
            //根据图书Id查询图书信息
            Book book = bookService.getBook(bookid);
            //将获取到的图书信息链表保存在request域中，传递给前端
            ArrayList<Book> list = new ArrayList<>();
            list.add(book);
            //存到request域中，传递给前端
            request.setAttribute("book", book);
            //请求跳转
            request.getRequestDispatcher("/getBookById.jsp").forward(request, response);
        }else {
            response.sendRedirect("/listBookServlet");
            return;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
